<template>
    <div class="sendMSMPage">
      <div class="tree-wrap tree-msm">
        <div class="search-ctrl f-l" >
        <input type="text" class="search-text query-msm-search"
               v-model="searchStr"
               placeholder="搜索部门名称或警员姓名">
        <button type="button"
                @click="searchBtn"
                style="right: 46px;"
                class="search-btn btn btn-info" >搜索</button>
        <button type="button"
                @click="clearSearBtn"
                style="right: 4px;"
                class="search-btn btn btn-info" >清空</button>
        </div>
        <div class="tree-content" style="height:100%">
          <div id="tree-dep" class="ztree div-tree"></div>
        </div>
      </div>
      <div class="content-wrap">
        <div class="top-page">
          <div v-show="allDataSum > 0">
            <label class="my_protocol">
              <input
                class="input_agreement_protocol"
                type="checkbox"
                :checked="checkIds.length === addressPageList.length && addressPageList.length != 0"
                @click="checkedAll()"/>
              <span></span>
              <p class="all-checkbox">全选</p>
            </label>
          </div>
          <!-- 分页 -->
          <pages class="pages"
                 :showItem = showItem
                 :allpage = allpage
                 :pageSize = pageSize
                 :allDataSum = allDataSum
                 @current-change = currentChange >
          </pages>
          <!-- 分页闭合 -->
          <!-- 通讯录人员 -->
          <ul class="address-people-wrap-ul">
            <li v-for="item in addressPageList"
                class="address-people-wrap"
            >
              <label class="my_protocol">
                <input
                  class="input_agreement_protocol"
                  type="checkbox"
                  :checked="checkIds.indexOf(item.id) > -1"
                  @click="checkedOne(item.id)"/>
                <span></span>
                <div class="address-people-detail" >
                  <div class="user-img-wrap">
                    <img class="user-img" :src="userImgSrc(item.pictureUrl)"  :onerror="PicErr">
                  </div>
                  <span class="people-name"
                        v-text="item.name+' ('+item.policeCode+')'"></span>
                  <span class="people-phone" v-text="item.policePhone"></span>
                </div>
              </label>
            </li>
          </ul>
          <!-- 通讯录人员 end -->

        </div>
        <div class="bottom-page">
          <div>
            <div class="addressee">
              <div class="addressee-detail">
                <span class="addressee-title">收件人：</span>
                <div class="addressee-item"
                    v-for="(item,index) in addressData" :key="item.id">
                  <span v-text="item.name"></span>
                  <span v-text="item.policePhone"></span>
                  <span class="span-x"
                        @click="spanX(index,item.id)">×</span>
                </div>
              </div>
            </div>
            <div class="input-addressee-wrap">
              <input class="input-addressee"
                     placeholder="在此可输入增加的收件人号码（格式一：姓名 电话；格式二：电话）"
                     v-model="inputAddressee"
                     type="text">
              <button class="btn btn-success input-addressee-btn"
                      @click="addAddresseeBtn">+添加到收件人</button>
            </div>
            <textarea class="text-message-content"
                      v-model="textareaStr"
                      cols="30" rows="10">
            </textarea>
            <button class="btn btn-info f-r" @click="sendFn">
              <span class="glyphicon glyphicon-align-left glyphicon-send" aria-hidden="true"></span>&nbsp;&nbsp;发送
            </button>
            <button
              class="btn btn-primary f-r auto-pencil"
              v-show="Businesskey&&Businesskey.length > 0"
              @click="autoEditFn"
            >
              <span class="glyphicon glyphicon-pencil" aria-hidden="true"></span>&nbsp;&nbsp;根据警情自动生成短信
            </button>
          </div>

        </div>
      </div>
    </div>
</template>

<script>
  import pages from './pages';


  export default {
    name: "sendMSMPage",
    data(){
      return {
        setting : {
          data: {
            simpleData: {
              enable: true
            },
          },
          view: {
            showIcon: false,
            selectedMulti: false,
            dblClickExpand: false,
          },
          callback: {
            onClick: this.zTreeOnClick,
          }
        },
        // 分页数据
        showItem: 10,       //分页条下面item的数目
        allpage: 0,         //根据每页数据/总数据得到的总页数
        pageSize: 10,       //每页数据
        allDataSum: 0,      //总数据

        stationId: '',       // 点击树获得的部门id
        addressPageList: [], // 警员数据列表
        PicErr: 'this.src='+require("@/../static/img/Policeman.png"),  //img加载失败的图片
        checkIds: [],     // 点击的警员数据存放
        isCheckedAll: false, // 判断是否为全选
        addressData: [],     // 添加到 收件人 箭头 的数据
        inputAddressee: '',  // 添加到收件人输入框
        textareaStr: '',
        searchStr: '',       // 搜索字符串
        //wpf参数
        Businesskey: '',     // 警情id  wpf 点击的字段
        UserId: '',          // 登陆人id
        InstructID: '',      // 指令id
        TaskID: '',          // 任务ids
      }
    },
    components:{
      pages,
    },
    mounted(){
      // 初始化加载树结构
      let cookieObj = this.getcookie();
      this.Businesskey = cookieObj.Businesskey;
      // this.Businesskey = 'test';
      this.UserId = cookieObj.UserId;
      this.InstructID = cookieObj.InstructID;
      this.TaskID = cookieObj.TaskID;
      //alert("UserId:"+this.UserId);
      // this.s_alert(cookieObj)
      // this.s_alert(document.cookie)
      if (this.Businesskey && this.Businesskey.length > 0) {
        this.autoEditFn()
      }
      this.treeAjax(baseURL+'api/jp-BIRM-UserProfile-ms/addressbook/maillist/findalldata','get',"clear");
    },
    methods:{
      // 搜索框搜索事件
      searchBtn(){
        this.addressPageList = []
        if(this.searchStr.length>0){
          this.treeAjax(baseURL+'api/jp-BIRM-UserProfile-ms/addressbook/search/findbykeywords?keyWord='+this.searchStr,"get","search")
        }else {
          this.treeAjax(baseURL+'api/jp-BIRM-UserProfile-ms/addressbook/maillist/findalldata','get',"clear");
        }
      },
      // 搜索框清除事件
      clearSearBtn(){
        this.addressPageList = []
        this.searchStr = '';
        this.treeAjax(baseURL+'api/jp-BIRM-UserProfile-ms/addressbook/maillist/findalldata','get',"clear");
      },
      //树结构加载
      treeAjax(url,type,flag){
        this.s_loading(true)
        this.$axios[type](url)
          .then((data)=>{
            // $.fn.zTree.init($("#tree-dep"), this.setting, data.data.data);
            this.s_loading(false)
            let tepData = this.addPeopelNumAfterStationName(data.data);
            let stationData = [];
            tepData.forEach(function(item){
              if(item.hasOwnProperty('type')){
                stationData.push(item);
              }
            });
            let treeObj = $("#tree-dep");
            if(flag === "search"){
              $.fn.zTree.init($("#tree-dep"), this.setting, data.data);
              $(function(){
                $("#tree-dep > li").eq(0).children("a").click();
              });
            }else if(flag === "clear"){
              $.fn.zTree.init($("#tree-dep"), this.setting, stationData);
            }
          })
          .catch((err)=>{
            this.s_loading(false)
            //console.log(err);
          })
      },
      // 当树的某项被点击
      zTreeOnClick(evt, treeId, treeNode){
        if(treeNode.hasOwnProperty('policeCode')){  // 是警员
          let item = {
            name: treeNode.name,
            policePhone: treeNode.policePhone,
            id: treeNode.id
          }
          this.onlineOne(item)
        }else {
          this.stationId = treeNode.id;
          this.axiosAddressPageListFn(1);
        }
      },
      checkboxChange(index){
        //console.log(index)
      },
      axiosAddressPageListFn(page){
        //显示对应部门的通讯录人员
        this.s_loading(true)
        this.$axios.get(baseURL+'api/jp-BIRM-UserProfile-ms/addressbook/maillist/findmaillistbystationid/'+this.stationId+'?page='+page+'&pageSize='+this.pageSize)
          .then(res => {
            this.addressPageList = res.data.list;
            this.checkIds = []
            // 切换开始转为false
            this.isCheckedAll = false
            this.allDataSum = res.data.total;
            this.allpage = Math.ceil(res.data.total/this.pageSize);
            this.curPageChangeIsChecked()
            this.s_loading(false)
            //console.log(this.addressPageList);
          })
      },
      currentChange(current) {
        this.axiosAddressPageListFn(current);
      },
      userImgSrc(userImgSrc){
        if(userImgSrc){
          return  baseURL                         //运行环境
            + 'api/jp-TIFS-FileCenter-ms/file?businessId='  //微服务地址
            + userImgSrc;
        }else {
          return require('@/../static/img/Policeman.png');
        }
      },
      onlineOne (item) {
        let alone = this.addressData.filter(data => {
          return item.id == data.id
        })
        // debugger
        if (alone.length == 0){
          this.addressData.push(item);
        } else {
          this.s_alert('此警员已经添加')
        }
      },
      // 单选框全选事件
      checkedAll(){
        this.isCheckedAll = !this.isCheckedAll;
        if(this.isCheckedAll){
          // 全选时
          this.checkIds = [];
          this.addressPageList.forEach(function(item){
            this.checkIds.push(item.id);
            this.onlineOne(item)
          }, this)
        }
        else {
          // 全选取消
          this.checkIds = [];
          // 这个时候显示的数据只切掉当前页面的
          this.addressPageList.map(itemPage => {
            this.addressData.map((itemData, index) => {
              if (itemPage.id == itemData.id) {
                this.addressData.splice(index, 1)
              }
            })
          })
        }
        // //console.log(this.checkIds);
        //console.log(this.addressData);
      },
      // 单选框全选事件
      checkedOne(id){
        let idIndex = this.checkIds.indexOf(id);
        if(idIndex >= 0){
          // 如果已经包含该id，则去除（单选按钮由选中变为非选中状态）
          this.checkIds.splice(idIndex, 1);
          for(let i = 0; i < this.addressData.length; i++){
            if(this.addressData[i].id == id){
              this.addressData.splice(i, 1);
            }
          }
        }
        else {
          // 选中该checkbox
          this.checkIds.push(id);
          for(let i = 0; i < this.addressPageList.length; i++){
            if(this.addressPageList[i].id == id){
              this.addressData.push(this.addressPageList[i]);
            }
          }
        }

      },
      // x号点击事件
      spanX(index, id){
        this.addressData.splice(index,1);
        let idIndex = this.checkIds.indexOf(id);
        if(idIndex>-1){
          this.checkIds.splice(idIndex, 1);
        }
      },
      // 添加到收件人 按钮
      addAddresseeBtn(){
        let ary = this.inputAddressee.split(' ');
        /*
          id: "37CBB010774F46978C22B7A23084649A"
          name: "阮臻"
          pId: "126"
          pictureUrl: null
          policeCode: "073954"
          policePhone: "13972897969"
          policePosition: null
          policeRadioId: null
          sort: null
        */
        if (this.inputAddressee === '') {
          this.s_alert("请填写收件人信息")
          return false
        } else if(ary.length === 1){
          if(this.verifyForm.iphone(ary[0])){
            this.s_alert("输入手机号不正确");
            return false;
          }
          let item = {
            "policePhone": ary[0]
          }
          this.addressData.push(item);
        }else if(ary.length === 2){
          if(this.verifyForm.iphone(ary[1])){
            this.s_alert("输入手机号不正确");
            return false;
          }
          let item = {
            "name":ary[0],
            "policePhone": ary[1]
          }
          this.addressData.push(item);
        }
        this.inputAddressee = '';
      },
      // 发送按钮
      sendFn(){
        if(!this.textareaStr.length>0){
          this.s_alert('请填写短信信息！')
          return false;
        }
        if(!this.addressData.length>0){
          this.s_alert('请选择联系人！')
          return false;
        }
        let sendPersonList = [];
        this.addressData.forEach(item => {
          sendPersonList.push({
            "phone": item.policePhone,
            "policeGuid": item['id'],
            "policeName": item['name']
          })
        })
        if(s_test){
          this.UserId = '117'
          this.InstructID = 'c2c5e700-5f17-4c22-8ae0-65ad5472a041'
        }
        let data ={
          "businessKey": this.Businesskey,
          "messageContent": this.textareaStr,
          "sendPersonList": sendPersonList,
          "userId": this.UserId,
          "instructionId": this.InstructID,
          "taskId": this.TaskID,
        };
        let url;
        if (sendSomeMSMUrl === 'WeiFang') { // 潍坊的地址是特别的
          url = baseURL+'api/jp-BSPA-PolSituInfo-ms/shortmessage/sendmessage';
        } else {
          url = baseURL+'api/jp-BSPA-PolSituInfo-ms/message/shortmessage/sendmessage';
        }
        this.$axios({
          method: 'post',
          url: url,
          data:data,
        }).then(res => {
            this.s_alert("短信发送中......");
            this.clearFn();
            //console.log(res);
          }).catch(err => {
            this.s_alert("发送接口出错，请联系管理员")
        })
        //console.log(this.textareaStr)
      },
      // 自动编辑按钮
      autoEditFn(){
        //this.Businesskey
        // this.s_alert(this.Businesskey)
        let url;
        if(sendSomeMSMUrl === 'WeiFang') { // 潍坊的地址是特别的
          url = baseURL+"api/jp-BSPA-PolSituInfo-ms/shortmessage/automessage/"+this.Businesskey
        }else {
          url = baseURL+"api/jp-BSPA-PolSituInfo-ms/message/automessage/create/"+this.Businesskey
        }

        this.$axios.get(url)
          .then(res => {
            this.textareaStr = res.data;
          })
          .catch(err => {
            this.s_alert("自动编辑接口问题，自动编辑失败")
            //console.log(err);
          })

      },
      // 分页过后，判断勾选状态
      curPageChangeIsChecked () {
        this.addressPageList.map(itemPage => {
          this.addressData.map(itemData => {
            if (itemPage.id == itemData.id){
              this.checkIds.push(itemPage.id)
            }
          })
        })
        // 该变全选的状态
        if(this.checkIds.length > 0 && this.checkIds.length == this.addressPageList.length){
          this.isCheckedAll = true
        }
      },
      // 清除函数
      clearFn() {
        this.checkIds = [];    // 点击的警员数据存放
        this.addressData =  [];     // 添加到 收件人 箭头 的数据
        this.inputAddressee = '';  // 添加到收件人输入框
        this.textareaStr = '';

      }

    }, // end methods
    computed: {

    }
  }
</script>

<style lang="scss" scoped>
  .sendMSMPage {
    display: flex;
    padding-top: 50px;
    .tree-msm {
      border: 2px solid #005fac;
      background-color: #00294a;
    }
    .content-wrap {
      width: calc(100% - 300px);
      height: 100%;
      border-top: 2px solid #0060aa;
      border-right: 2px solid #0060aa;
      border-bottom: 2px solid #0060aa;
      background-color: #002f56;
      .top-page, .bottom-page {
        width: 100%;
        height: 50%;
      }
      .top-page {
        border-bottom: 2px solid #005fac;
        padding: 10px;
        .address-people-wrap-ul {
          display: flex;
          flex-wrap: wrap;
        }
        .address-people-wrap {
          position: relative;
          width: 374px;
          height: 42px;
          flex: 1 1 50%;
          .address-people-detail {
            display: inline-block;
            width: 338px;
            border: 1px solid #0f76d8;
            background-color: #013162;
            color: #fff;
            font-weight: 400;
            line-height: 40px;
            font-size: 16px;
            .people-name {
              margin-left: 10px;
            }
            .people-phone {
              float: right;
              margin-right: 10px;
              color: #29a2ff;
            }
          }
        }
      }
      .bottom-page {
        padding: 20px;
        overflow-y: auto;
        .addressee {
          position: relative;
          color: #fff;

          .addressee-detail {
            display: inline-block;
            .addressee-title {
              font-size: 14px;
              line-height: 28px;
            }
            .addressee-item {
              position: relative;
              display: inline-block;
              height: 28px;
              line-height: 28px;
              font-size: 14px;
              padding: 0 24px 0 10px;
              border-left:1px solid #0d7fff ;
              border-top:1px solid #0d7fff ;
              border-bottom:1px solid #0d7fff ;
              margin: 0 22px 10px 0;
              background-color: #00366c;
              &:before {
                content:'';
                position: absolute;
                right: -28px;
                width: 0;
                height: 0;
                bottom: -1px;
                border-top: 14px solid transparent;
                border-left: 14px solid #0d7fff;
                border-right: 14px solid transparent;
                border-bottom: 14px solid transparent;
              }
              &:after {
                content:'';
                position: absolute;
                right: -27px;
                width: 0;
                height: 0;
                bottom: -1px;
                border-top: 14px solid transparent;
                border-left: 14px solid #00366c;
                border-right: 14px solid transparent;
                border-bottom: 14px solid transparent;
              }
              .span-x {
                position: absolute;
                top: 0;
                right: -10px;
                padding: 0 10px;
                cursor: pointer;
              }
            }
          }
        }
        .input-addressee-wrap {
          position: relative;
          .input-addressee {
            width: 86%;
            height: 30px;
            border: 1px solid #004f9f;
            margin-top: 16px;
            background-color: #00366c;
            color: #fff;
            &::-webkit-input-placeholder{
              color: #006ee6;
            }
          }
          .input-addressee-btn {
            position: absolute;
            bottom: 0;
            right: 0;
            height: 32px;
            font-size: 14px;
            line-height: 14px;
            padding: 0 10px;
          }
        }
        .text-message-content {
          width: 100%;
          height: 170px;
          margin-top: 10px;
          color: #fff;
          resize: none;
          border: 1px solid #004f9f;
          background-color: #00366c;
        }

       }
    }
  }
  .query-msm-search{
    &::-webkit-input-placeholder{
      color: #006ee6 !important;
    }
  }
  .user-img-wrap {
    display: inline-block;
    margin-left: 4px;
    width: 38px;
    height: 38px;
    border-radius: 50%;
    border: 1px solid #0f76d8;
    background-color: #002d77;
    .user-img {
      width: 36px;
      height: 31px;
      border-radius: 50%;
      display: inline-block;
    }
  }
  .tree-wrap {
    width: 300px;
    height: 100%;
  }
  .div-tree {
    width: 100%;
    height: 100%;
    overflow-y: auto;
    float: left;
    padding-bottom: 40px;
    &::-webkit-scrollbar {
    display: none;
    }

  }
  .all-checkbox {
    position: relative;
    top: 4px;
    display: inline-block;
    font-size: 16px;
    color: #fff;
  }
  .auto-pencil {
    margin-right: 6px;
  }
  .main-controller-body.wpf  .query-msm-search {
    width: 210px ;
  }
  /*隐藏掉我们模型的checkbox*/
  .my_protocol .input_agreement_protocol {
    appearance: none;
    -webkit-appearance: none;
    outline: none;
    display: none;
  }
  /*未选中时*/
  .my_protocol .input_agreement_protocol+span {
    width: 20px;
    height: 20px;
    display: inline-block;
    background: url(./../../../assets/icon_checkbox.png) no-repeat;
    background-position-x: 0px;
    background-position-y: -25px;
    position: relative;
    top: 8px;
  }
  /*选中checkbox时,修改背景图片的位置*/
  .my_protocol .input_agreement_protocol:checked+span {
    background-position: 0 0px
  }
</style>
